<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Welcome extends Controller_Template
{

	public $template = 'template/index';


	public
	function before()
	{
		parent::before();
		$this->template->styles = Kohana::$config->load('names.styles');
		$this->template->scripts = Kohana::$config->load('names.scripts');

		$this->template->title = 'Галлерея изображений';
		$this->template->content = '';
		$this->template->preload_images  = array();
	}

	public function action_index()
	{


		$count = ORM::factory('orm_images')->count_all();
		$pagination = Pagination::factory(array(
			'total_items' => $count,
		))->route_params(array(
			'controller' => Request::current()->controller(),
			'action' => Request::current()->action(),
		));


		$data = ORM::factory('orm_images')
			->limit($pagination->items_per_page)
			->offset($pagination->offset)
			->find_all();

		#Kohana::$config->load('names.picture.small.path') . $value->file
		foreach($data as $value){
			$value->generate_image();
			$this->template->preload_images[$value->id] = '/' . Kohana::$config->load('names.picture.small.path') . $value->file;
		}

		$this->template->content = new View('gallery/index', array(
			'data' => $data,
			'pagination' => $pagination
		));
	}

	public function action_add()
	{
		$content_array = array();

		$this->template->title = 'Добавление изображения';

		if(count($this->request->post()) > 0){
			if ($_FILES['file']['error'] == UPLOAD_ERR_OK AND Upload::type($_FILES['file'], Kohana::$config->load('names.picture.allowed'))) {
				$path_download = Kohana::$config->load('names.picture.path');
				$new_name = Helper_Default::new_name(DOCROOT . $path_download, $_FILES['file']['name']);
				Upload::save($_FILES['file'], $new_name, DOCROOT . $path_download);
				Model_Orm_Images::item_save(array(
					'text' => strip_tags($this->request->post('text')),
					'file' => $new_name,
				));
				$content_array['success'] = TRUE;
			}
			else{
				$content_array['error'] = TRUE;
			}
		}

		$this->template->content = new View('gallery/add',
			$content_array
		);
	}

	public function action_ajax(){

		if($this->request->post('image_id') > 0){
			$data = ORM::factory('orm_images')->where('id', '=', (int)$this->request->post('image_id'))->find();
			if ($data->loaded()) {
				echo new View('gallery/ajax', array('data' => $data));
				exit;
			}
		}
		echo 'Данные изображения не найдены.';
		exit;
	}

} // End Welcome
